package com.example.shiro.demo.web;

import com.alibaba.fastjson.JSONObject;
import com.example.shiro.demo.entity.Role;
import com.example.shiro.demo.entity.User;
import com.example.shiro.demo.service.ILoginService;
import com.example.shiro.demo.shiro.ShiroUtil;
import com.example.shiro.demo.vo.ActiveUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * <Description> <br>
 *
 * @author renweiping<br>
 * @version 1.0<br>
 * @taskId: <br>
 * @createDate 2019/10/14 13:16 <br>
 * @see com.example.shiro.demo <br>
 */
@RestController
public class LoginResource {

    @Autowired
    private ILoginService loginService;

    //退出的时候是get请求，主要是用于退出
    //@RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    //post登录
    //@RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String login2(@RequestBody Map map) {
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        //进行验证，这里可以捕获异常，然后返回对应信息
        JSONObject jsonObject = new JSONObject();
        if (!subject.isAuthenticated()) {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                    map.get("username").toString(),
                    map.get("password").toString());
            Object rememberMe = map.get("rememberMe");
            if (rememberMe != null && StringUtils.hasText(rememberMe.toString())) {
                usernamePasswordToken.setRememberMe(true);
            }
            try {
                subject.login(usernamePasswordToken);
                String sessionId = subject.getSession().getId() != null ? subject.getSession().getId().toString() : "";
                jsonObject.put("token", subject.getSession().getId());
                jsonObject.put("sessionId", sessionId);
                jsonObject.put("msg", "登录成功");
            } catch (IncorrectCredentialsException e) {
                jsonObject.put("msg", "密码错误");
            } catch (LockedAccountException e) {
                jsonObject.put("msg", "登录失败，该用户已被冻结");
            } catch (AuthenticationException e) {
                jsonObject.put("msg", "该用户不存在");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            String sessionId = (String) subject.getSession().getId();
            jsonObject.put("token", subject.getSession().getId());
            jsonObject.put("sessionId", sessionId);
            jsonObject.put("msg", "已经登录了");
        }
        return jsonObject.toString();
    }


    //post登录
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public String login(@RequestBody Map map, HttpServletResponse res) {
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        //进行验证，这里可以捕获异常，然后返回对应信息
        JSONObject jsonObject = new JSONObject();
        if (!subject.isAuthenticated()) {
            try {
                jsonObject = loginService.login(map.get("username").toString(),
                        Integer.valueOf(map.get("password").toString()), res);
                jsonObject.put("msg", "登录成功");
            } catch (IncorrectCredentialsException e) {
                jsonObject.put("msg", "密码错误");
            } catch (LockedAccountException e) {
                jsonObject.put("msg", "登录失败，该用户已被冻结");
            } catch (AuthenticationException e) {
                jsonObject.put("msg", "该用户不存在");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            String sessionId = (String) subject.getSession().getId();
            jsonObject.put("token", subject.getSession().getId());
            jsonObject.put("sessionId", sessionId);
            jsonObject.put("msg", "已经登录了");
        }
        return jsonObject.toString();
    }


    @RequestMapping(value = "/index")
    public String index() {
        return "index";
    }

    //登出
    @RequestMapping(value = "/logout")
    public String logout() {
        return "logout";
    }

    //错误页面展示
    @RequestMapping(value = "/error", method = RequestMethod.POST)
    public String error() {
        return "error ok!";
    }

    //数据初始化
    @RequestMapping(value = "/addUser")
    public String addUser(@RequestBody Map<String, Object> map) {
        User user = loginService.addUser(map);
        return "addUser is ok! \n" + user;
    }

    //角色初始化
    @RequestMapping(value = "/addRole")
    public String addRole(@RequestBody Map<String, Object> map) {
        Role role = loginService.addRole(map);
        return "addRole is ok! \n" + role;
    }

    //注解的使用
    @RequiresRoles("admin")
    @RequiresPermissions("create")
    @RequestMapping(value = "/create")
    public String create(HttpServletRequest request) {

        Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
        if (null == cookies) {
            System.out.println("没有cookie=========");
        } else {
            for (Cookie cookie : cookies) {
                System.out.println("name:" + cookie.getName() + ",value:" + cookie.getValue());
            }
        }


        return "Create success!" + new Date();
    }


    //注解的使用
    @RequiresRoles("user")
    @RequiresPermissions("read")
    @RequestMapping(value = "/read")
    public String read(HttpServletRequest request) {

        Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
        if (null == cookies) {
            System.out.println("没有cookie=========");
        } else {
            for (Cookie cookie : cookies) {
                System.out.println("name:" + cookie.getName() + ",value:" + cookie.getValue());
            }
        }


        return "Create success!" + new Date();
    }

}
